﻿using OldPlatform_Data_Clean.entity;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OldPlatform_Data_Clean
{
    public partial class MainForm : Form
    {
        private static readonly string CONNStr = @"server={0};uid={1};pwd={2};database={3}";
        private string dtFormat = "yyyy/MM/dd";
        private List<string> ErrorTableList = new List<string>();
        private SqlSugarClient oldDb;
        private List<string> paramTable = new List<string>();
        private List<string> selTable = new List<string>();
        private long SumCount = 0;
        private double SumTimes = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            if (tbOldServerIp.Text == "")
            {
                MessageBox.Show("服务器ip不能为空。");
                return;
            }
            if (tbOldUser.Text == "")
            {
                MessageBox.Show("服务器用户名不能为空。");
                return;
            }
            if (tbOldPwd.Text == "")
            {
                MessageBox.Show("服务器密码不能为空。");
                return;
            }
            if (cbbOldDB.Text == "")
            {
                MessageBox.Show("数据库名称不能为空。");
                return;
            }

            try
            {
                // 连接源数据库
                oldDb = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = string.Format(CONNStr, tbOldServerIp.Text, tbOldUser.Text, tbOldPwd.Text, cbbOldDB.Text),
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true,
                }, db =>
                {
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                    };
                });
                if (!oldDb.Ado.IsValidConnection())
                {
                    MessageBox.Show("数据库连接失败，请检查配置");
                    return;
                }
                MessageBox.Show("数据库连接成功。", "提示框");
                groupBox4.Enabled = true;
                panel1.Enabled = true;
                btnDisConn.Enabled = true;
                btnConn.Enabled = false;
                groupBox2.Enabled = false;
            }
            catch (Exception ex)
            {
                // 抛出异常
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDataMigration_Click(object sender, EventArgs e)
        {
            if (selTable == null || selTable.Count == 0)
            {
                MessageBox.Show("请先选择需要清理的数据");
                return;
            }

            DialogResult res = MessageBox.Show("数据清理会删除目标数据库时间范围内的相关表的数据，\r\n确定开始清理吗？", "确认框", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res != DialogResult.OK)
            {
                return;
            }

            btnDataClear.Enabled = false;
            groupBox1.Enabled = false;
            groupBox4.Enabled = false;

            // 创建线程
            Task.Factory.StartNew(async () =>
            {
                bool isHis = false;
                foreach (string item in selTable)
                {
                    if (item == TableConstant.hourRpt)
                    {
                        // 清理小时报数据
                        await DataClean("小时报");
                    }
                    else if (item == TableConstant.shiftRpt)
                    {
                        // 清理班报数据
                        await DataClean("班报");
                    }
                    else if (item == TableConstant.dayRpt)
                    {
                        // 清理日报数据
                        await DataClean("日报");
                    }
                    else if (item == TableConstant.processData)
                    {
                        // 清理工艺数据
                        await DataClean("工艺");
                    }
                    else if (item == TableConstant.effectData)
                    {
                        // 清理效应记录数据
                        await DataClean("效应记录");
                    }
                    else if (item == TableConstant.faultData)
                    {
                        // 清理故障记录数据
                        await DataClean("故障记录");
                    }
                    else if (item == TableConstant.operateData)
                    {
                        // 清理人工操作记录数据
                        await DataClean("人工操作记录");
                    }
                    else if (item == TableConstant.paramChangeData)
                    {
                        // 清理参数修改记录数据
                        await DataClean("参数修改记录");
                    }
                    else if (item == TableConstant.historyData)
                    {
                        isHis = true;
                        // 清理历史数据
                        await CleanHistoryAnsyc();
                    }
                }
                if (!isHis)
                {
                    statusLabel.Text = string.Format("清理完成，共：{0}条数据。耗时：{1}秒", SumCount, SumTimes);
                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                }
            });

            btnDataClear.Enabled = true;
            groupBox1.Enabled = true;
            groupBox4.Enabled = true;
        }

        private void btnDisConn_Click(object sender, EventArgs e)
        {
            if (oldDb != null)
            {
                oldDb.Close();
            }
            groupBox4.Enabled = false;
            panel1.Enabled = false;
            btnConn.Enabled = true;
            btnDisConn.Enabled = false;
            groupBox2.Enabled = true;
        }

        private void cbbSelDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbbSelDate.SelectedIndex)
            {
                case 1:
                    dtpEnd.Value = DateTime.Today.AddMonths(-1);
                    break;

                case 2:
                    dtpEnd.Value = DateTime.Today.AddMonths(-3);
                    break;

                case 3:
                    dtpEnd.Value = DateTime.Today.AddMonths(-6);
                    break;

                case 4:
                    dtpEnd.Value = DateTime.Today.AddYears(-1);
                    break;

                case 5:
                    dtpEnd.Value = DateTime.Today.AddYears(-2);
                    break;

                case 6:
                    dtpEnd.Value = DateTime.Today.AddYears(-3);
                    break;

                default:
                    dtpEnd.Value = DateTime.Today.AddMonths(-1);
                    break;
            }
        }

        private void ccbDayRpt_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbDayRpt.Checked)
            {
                selTable.Add(TableConstant.dayRpt);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.dayRpt);
            }
        }

        private void ccbEffectData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbEffectData.Checked)
            {
                selTable.Add(TableConstant.effectData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.effectData);
            }
        }

        private void ccbFaultData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbFaultData.Checked)
            {
                selTable.Add(TableConstant.faultData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.faultData);
            }
        }

        private void ccbHistory_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbHistory.Checked)
            {
                selTable.Add(TableConstant.historyData);
                ccbHourRpt.Checked = false;
                ccbShiftRpt.Checked = false;
                ccbDayRpt.Checked = false;
                ccbProcessData.Checked = false;
                ccbEffectData.Checked = false;
                ccbFaultData.Checked = false;
                ccbOperateData.Checked = false;
                ccbParamChangeData.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.historyData);
            }
        }

        private void ccbHourRpt_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbHourRpt.Checked)
            {
                selTable.Add(TableConstant.hourRpt);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.hourRpt);
            }
        }

        private void ccbOperateData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbOperateData.Checked)
            {
                selTable.Add(TableConstant.operateData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.operateData);
            }
        }

        private void ccbParamChangeData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbParamChangeData.Checked)
            {
                selTable.Add(TableConstant.paramChangeData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.paramChangeData);
            }
        }

        private void ccbProcessData_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbProcessData.Checked)
            {
                selTable.Add(TableConstant.processData);
                ccbHistory.Checked = false;
            }
            else
            {
                selTable.Remove(TableConstant.processData);
            }
        }

        private void ccbSelectAll_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbSelectAll.Checked)
            {
                ccbHourRpt.Checked = true;
                ccbShiftRpt.Checked = true;
                ccbDayRpt.Checked = true;
                ccbProcessData.Checked = true;
                ccbEffectData.Checked = true;
                ccbFaultData.Checked = true;
                ccbOperateData.Checked = true;
                ccbParamChangeData.Checked = true;
            }
            else
            {
                ccbHourRpt.Checked = false;
                ccbShiftRpt.Checked = false;
                ccbDayRpt.Checked = false;
                ccbProcessData.Checked = false;
                ccbEffectData.Checked = false;
                ccbFaultData.Checked = false;
                ccbOperateData.Checked = false;
                ccbParamChangeData.Checked = false;
                ccbHistory.Checked = false;
            }
        }

        private void ccbShiftRpt_CheckStateChanged(object sender, EventArgs e)
        {
            if (ccbShiftRpt.Checked)
            {
                selTable.Add(TableConstant.shiftRpt);
            }
            else
            {
                selTable.Remove(TableConstant.shiftRpt);
            }
        }

        private void dtpEnd_ValueChanged(object sender, EventArgs e)
        {
            if (dtpEnd.Value > DateTime.Today.AddMonths(-1))
            {
                dtpEnd.Value = DateTime.Today.AddMonths(-1);
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            groupBox4.Enabled = false;
            panel1.Enabled = false;
            btnDisConn.Enabled = false;
            statusLabel.Text = "";
            cbbSelDate.SelectedIndex = 0;
            dtpEnd.Value = DateTime.Today.AddMonths(-1);
            dtpEnd.MaxDate = DateTime.Today.AddMonths(-1);
            tbOldServerIp.Text = "192.168.1.201";
            tbOldUser.Text = "sa";
            tbOldPwd.Text = "sa";
            cbbOldDB.SelectedIndex = 0;
            paramTable.Clear();
            paramTable.Add(TableConstant.addressParam);
            paramTable.Add(TableConstant.depthParam);
            paramTable.Add(TableConstant.productParam);
            paramTable.Add(TableConstant.systemParam);
            this.Text = this.Text + " V" + Application.ProductVersion;
        }

        /// <summary>
        /// 数据清理
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        private async Task DataClean(string type)
        {
            try
            {
                DateTime dt1 = dtpEnd.Value;
                if (dt1 < DateTime.Today.AddMonths(-1))
                    // 查询数据
                    if (type == "小时报")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<HourRpt>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<HourRpt>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "班报")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<ShiftRpt>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<ShiftRpt>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "日报")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<DayRpt>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<DayRpt>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "工艺")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<ProcessData>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<ProcessData>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = DateTime.Now - tStart;
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "效应记录")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<EffectData>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<EffectData>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = DateTime.Now - tStart;
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "故障记录")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<FaultData>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<FaultData>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = (TimeSpan)(DateTime.Now - tStart);
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "人工操作记录")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<OperateData>()
                        .Where(it => SqlFunc.LessThan(it.Operate_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<OperateData>().Where(it => SqlFunc.LessThan(it.Operate_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = DateTime.Now - tStart;
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
                    else if (type == "参数修改记录")
                    {
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始查询{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        DateTime tStart = DateTime.Now;
                        var list = await oldDb.Queryable<ParamChangeData>()
                        .Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ToListAsync();
                        if (list == null || list.Count == 0)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    tbMemo.AppendText(string.Format("没有{0}数据...\r\n", type));
                                }));
                            }
                            return;
                        }
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("开始清理{0}之前的{1}数据...", dt1.ToString(dtFormat), type);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        // 开启事务
                        oldDb.Ado.BeginTran();
                        // 删除数据
                        oldDb.Deleteable<ParamChangeData>().Where(it => SqlFunc.LessThan(it.Record_date, dt1)).ExecuteCommand();
                        int count = list.Count;
                        // 提交事务
                        oldDb.Ado.CommitTran();
                        // 计算耗时
                        TimeSpan span = DateTime.Now - tStart;
                        double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                        if (InvokeRequired)
                        {
                            Invoke(new Action(() =>
                            {
                                statusLabel.Text = string.Format("{0}之前的{1}数据清理完成，清理{2}条。耗时：{3}秒", dt1.ToString(dtFormat), type, count, seconds);
                                tbMemo.AppendText(statusLabel.Text + "\r\n");
                            }));
                        }
                        SumCount += count;
                        SumTimes += seconds;
                    }
            }
            catch (Exception ex)
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(() =>
                    {
                        statusLabel.Text = string.Format("{0}数据清理失败，正在回滚...", type);
                        tbMemo.AppendText(string.Format("{0}数据清理失败，原因：{1}\r\n", type, ex.Message));
                    }));
                }
                // 回滚事务
                oldDb.Ado.RollbackTran();
            }
        }

        /// <summary>
        /// 清理历史数据
        /// </summary>
        /// <returns></returns>
        private async Task CleanHistoryAnsyc()
        {
            // 遍历日期查询表名
            DateTime dt1 = dtpEnd.Value;
            if (InvokeRequired)
            {
                Invoke(new Action(() =>
                {
                    statusLabel.Text = string.Format("查询{0}的历史数据表。", dt1.ToString(dtFormat));
                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                }));
            }
            string slotId = tb_slotId.Text.Trim();
            string dtFmt = dt1.ToString("yyyyMMdd");
            string sql = slotId == "" ? string.Format(@"select name from sys.tables where name like '%{0}'", dtFmt)
                : string.Format(@"select name from sys.tables where name = 'his_{0}{1}'", slotId, dtFmt);
            List<string> tbList = await oldDb.SqlQueryable<DbTableInfo>(sql).Select(it => it.Name).ToListAsync();
            if (tbList == null || tbList.Count == 0)
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(() =>
                    {
                        statusLabel.Text = "没有历史数据表。";
                        tbMemo.AppendText(statusLabel.Text + "\r\n");
                    }));
                }
                return;
            }
            // 遍历表
            foreach (string tb in tbList)
            {
                try
                {
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            tbMemo.AppendText("开始清理历史数据...\r\n");
                        }));
                    }
                    DateTime tStart = DateTime.Now;

                    // 判断目标数据表是否存在
                    bool tbExist = oldDb.DbMaintenance.IsAnyTable(tb);
                    // 开启事务
                    oldDb.Ado.BeginTran();
                    if (tbExist)
                    {
                        // 如果表存在，删除数据表
                        bool res = oldDb.DbMaintenance.DropTable<HistoryData>();
                        if (res)
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    statusLabel.Text = string.Format("历史数据表[{0}]删除成功。", tb);
                                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                                }));
                            }
                            SumCount += 1;
                        }
                        else
                        {
                            if (InvokeRequired)
                            {
                                Invoke(new Action(() =>
                                {
                                    statusLabel.Text = string.Format("历史数据表[{0}]删除失败。", tb);
                                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                                }));
                            }
                        }
                    }
                    // 提交事务
                    oldDb.Ado.CommitTran();
                    // 计算耗时
                    TimeSpan span = DateTime.Now - tStart;
                    double seconds = (double)(Math.Round(span.TotalSeconds * 1000)) / 1000;
                    SumTimes += seconds;
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("[{0}]的历史数据清理完成。耗时：{1}秒", tb, seconds);
                            tbMemo.AppendText(statusLabel.Text + "\r\n");
                        }));
                    }
                }
                catch (Exception ex)
                {
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            statusLabel.Text = string.Format("[{0}]的历史数据清理失败，正在回滚...", tb);
                            tbMemo.AppendText(string.Format("[{0}]的历史数据清理失败，原因：{1}\r\n", tb, ex.Message));
                        }));
                    }
                    // 回滚事务
                    oldDb.Ado.RollbackTran();
                    ErrorTableList.Add(tb);
                    continue;
                }
            }
            if (InvokeRequired)
            {
                Invoke(new Action(() =>
                {
                    statusLabel.Text = string.Format("历史数据清理完成。共删除：{0}个表，耗时：{1}秒", SumCount, SumTimes);
                    tbMemo.AppendText(statusLabel.Text + "\r\n");
                }));
            }
        }

        private void tbMemo_TextChanged(object sender, EventArgs e)
        {
            if (tbMemo.Lines.Length > 1000)
            {
                tbMemo.Lines[0] = "";
            }
        }
    }
}